import * as types from '../types'
import axios from 'axios'

const state = {
  posts: [],
  total: 0
}

const getters = {
  posts: state => state.posts,
  totalPosts: state => state.total
}

const mutations = {
  [types.POSTS_LOADED](state, data) {
    state.total = data.total || 0
    state.posts = data.posts || []
  }
}

const actions = {
  async searchPosts({
    commit
  }, query) {
    let response = await axios.post('/vts/search/posts', query)
    commit(types.POSTS_LOADED, response.data)
  },
  async savePost({
    commit
  }, data) {
    let response = await axios.post('/vts/post/save', data.form)
    if (response.data.accepted) data.callback(response.data.data)
  },
  async removePost({
    commit
  }, data) {
    let response = await axios.post('/vts/post/remove', {
      id: data.id
    })
    if (response.data.removed) data.callback()
  },
  async updatePostSticky({
    commit
  }, data) {
    let response = await axios.post('/vts/post/updateSticky', {
      id: data.id,
      top: data.top
    })
    if (response.data.accepted) data.callback()
  },
  async getPost({
    commit
  }, data) {
    let response = await axios.get('/vts/post/get/' + data.id)
    if (response.status === 200) data.callback(response.data)
  },
  async getPostReplies({
    commit
  }, data) {
    let response = await axios.get('/vts/post/replies/' + data.id)
    if (response.status === 200) data.callback(response.data)
  },
  async saveReply({
    commit
  }, data) {
    let response = await axios.post('/vts/post/reply', data.form)
    if (response.status === 200) data.callback(response.data)
  }
}

export default {
  state,
  mutations,
  getters,
  actions
}
